﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
using System.Globalization;

namespace GSMModemer
{
    public partial class MainForm : Form
    {
        public static SerialPort serPort;
        delegate void AddData(string _comBuffer);

        public MainForm()
        {
            InitializeComponent();
            serPort = new SerialPort();
            buttonSwitch.Text = "开启";
            textBoxCom.Text = "准备接收";
            buttonSmsSend.Enabled = false;
            buttonSmsSendStart.Enabled = false;
            buttonSmsSendCancle.Enabled = false;
            comboBoxSerNum.SelectedIndex = 0;
        }

        public bool SendCmd2SerPort(string _cmd)
        {
            string comString = _cmd + "\r";
            if (serPort.IsOpen)
            {
                try
                {
                    serPort.WriteLine(comString);
                    return true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return false;
                }
            }
            else
            {
                MessageBox.Show("串口没有打开！");
                return false;
            }
        }

        public bool SendCmd2SerPort(byte[] _cmd)
        {
            if (serPort.IsOpen)
            {
                try
                {
                    serPort.Write(_cmd, 0, 1);
                    return true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return false;
                }
            }
            else
            {
                MessageBox.Show("串口没有打开！");
                return false;
            }      
        }

        /// <summary>  
        /// 字符串转为UniCode码字符串  
        /// </summary>  
        /// <param name="s"></param>  
        /// <returns></returns>  
        public static string StringToUnicode(string s)
        {
            char[] charbuffers = s.ToCharArray();
            byte[] buffer;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < charbuffers.Length; i++)
            {
                buffer = System.Text.Encoding.Unicode.GetBytes(charbuffers[i].ToString());
                sb.Append(String.Format("//u{0:X2}{1:X2}", buffer[1], buffer[0]));
            }
            return sb.ToString();
        } 

        private void buttonSwitch_Click(object sender, EventArgs e)
        {
            if (serPort.IsOpen)
            {
                try
                {
                    serPort.Close();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
                buttonSwitch.Text = "开启";
                textBoxCom.AppendText("关闭串口");
                comboBoxSerNum.Enabled = true;
                labelStatus.Text = "串口已关闭";
                textBoxCom.ScrollToCaret();
            } 
            else
            {
                serPort.PortName = comboBoxSerNum.SelectedItem.ToString();
                serPort.BaudRate = 9600;
                serPort.ReadTimeout = 500;
                serPort.WriteTimeout = 500;
                serPort.Parity = Parity.None;
                serPort.StopBits = StopBits.One;
                serPort.DataBits = 8;
                serPort.Handshake = Handshake.None;
                serPort.DataReceived += new SerialDataReceivedEventHandler(serPort_DataReceived);

                try
                {
                    serPort.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
                buttonSwitch.Text = "关闭";
                textBoxCom.AppendText("\r\n打开串口\r\n");
                textBoxCom.ScrollToCaret();
                SendCmd2SerPort("AT");
                labelStatus.Text = "串口已打开";
                comboBoxSerNum.Enabled = false;

            }
        }
        private void textBoxComAddData(string _comBuffer)
        {
            textBoxCom.AppendText(_comBuffer);
            textBoxCom.ScrollToCaret();

        }

        private void serPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string comBuffer = sp.ReadExisting();
            AddData addData = new AddData(textBoxComAddData);
            this.Invoke(addData, new object[] { comBuffer });
        }

        private void buttonSmsFunction_Click(object sender, EventArgs e)
        {
            SendCmd2SerPort("AT+CMGF=1");
        }

        private void buttonSmsList_Click(object sender, EventArgs e)
        {
            SendCmd2SerPort("AT+CMGL=\"ALL\"");
        }

        private void buttonSmsTranslate_Click(object sender, EventArgs e)
        {
            string transBuffer = textBoxCom.Text;
            string[] split = Regex.Split(transBuffer, "\r\n", RegexOptions.IgnoreCase);
            
            

            foreach (string smsLine in split)
            {
                //判断是否是16进制，NO直接显示，YSE做处理.
                if (Regex.IsMatch(smsLine, "^[0-9A-Fa-f]+$") && (smsLine.Length % 4 == 0))
                {
                    string smsChinese = "";
                    byte[] converBuffer = new byte[2];
                    textBoxSmsChinese.AppendText("\r\n");
                    //textBoxSmsChinese.AppendText(smsLine);
                    for (int charindex = 0; charindex < smsLine.Length; charindex += 4)
                    {
                        converBuffer[1] = byte.Parse(smsLine.Substring(charindex, 2), NumberStyles.HexNumber);
                        converBuffer[0] = byte.Parse(smsLine.Substring(charindex + 2, 2), NumberStyles.HexNumber);
                        smsChinese += Encoding.Unicode.GetString(converBuffer);
                    }
                    textBoxSmsChinese.AppendText(smsChinese);
                } 
                else
                {
                    textBoxSmsChinese.AppendText("\r\n");
                    textBoxSmsChinese.AppendText(smsLine);
                }
            }

        }

        private void buttonSmsDelete_Click(object sender, EventArgs e)
        {
            SendCmd2SerPort(labelSmsDeleteCmd.Text);
        }

        private void comboBoxDeleteFlag_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxDeleteFlag.SelectedIndex == -1)
            {
                labelSmsDeleteCmd.Text = "AT+CMGD=" + textBoxDeleteIndex.Text;
            } 
            else
            {
                labelSmsDeleteCmd.Text = "AT+CMGD=" + textBoxDeleteIndex.Text + "," + comboBoxDeleteFlag.SelectedIndex.ToString();
            }
            
        }

        private void textBoxDeleteIndex_TextChanged(object sender, EventArgs e)
        {
            comboBoxDeleteFlag_SelectedIndexChanged(sender, e);
        }

        private void buttonCleanAll_Click(object sender, EventArgs e)
        {
            textBoxCom.Clear();
            textBoxSmsChinese.Clear();
        }

        private void buttonCmdInterface_Click(object sender, EventArgs e)
        {
            if (this.OwnedForms.Length == 0)
            {
                FormCmd formCmdInterface = new FormCmd(this);
                formCmdInterface.Owner = this;
                formCmdInterface.Show();
            } 
            else
            {
                this.OwnedForms[0].Activate();
            }

        }

        private void buttonSmsSendStart_Click(object sender, EventArgs e)
        {
            if (SendCmd2SerPort("AT+CMGS=\"" + textBoxSmsTeleNumber.Text + "\""))
            {
                buttonSmsSendCancle.Enabled = buttonSmsSend.Enabled = true;
            }
        }

        private void buttonSmsSendCancle_Click(object sender, EventArgs e)
        {
            byte[] _comByte = new byte[1];
            _comByte[0] = 0x1B;
            SendCmd2SerPort(_comByte);
            buttonSmsSendCancle.Enabled = buttonSmsSend.Enabled = false;
        }

        private void buttonSmsSend_Click(object sender, EventArgs e)
        {
            string _comstring = textBoxSmsContent.Text;
            if (Regex.IsMatch(_comstring, "[\u4e00-\u9fa5]"))
            {
                _comstring = StringToUnicode(_comstring);
            }
            
            _comstring = _comstring + "\x1A";
            if (SendCmd2SerPort(_comstring))
            {
                buttonSmsSendCancle.Enabled = buttonSmsSend.Enabled = false;
            }

            
        }

        private void textBoxSmsTeleNumber_TextChanged(object sender, EventArgs e)
        {
            if (textBoxSmsTeleNumber.Text.Length == 11)
                buttonSmsSendStart.Enabled = true;
            else
                buttonSmsSendStart.Enabled = false;
            
        }

        private void buttonSmsLanguageCN_Click(object sender, EventArgs e)
        {
            SendCmd2SerPort("AT+CSMP=17,167,0,8");
        }

        private void buttonSmsLanguageEN_Click(object sender, EventArgs e)
        {
            SendCmd2SerPort("AT+CSMP=17,167,0,0");
        }




    }
}
